package tr.com.netgis;

import tr.com.netgis.util.Constants;
import tr.com.netgis.util.Utility;
import tr.com.netgis.web.LoginRequest;
import tr.com.netgis.web.LoginResponse;
import tr.com.netgis.web.WebServisCaller;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author NetGis
 * 
 */
public class LoginActivity extends Activity implements OnClickListener {

	public static String SOURCE_KEY = "sourceActivity";
	
	private Button ok, back, exit;
	private TextView result, lblPassword;
	private EditText uname, pword;
	private String sourceActivityName;
	private ImageView imgPassword;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		Bundle bundle = getIntent().getExtras(); 
		sourceActivityName = bundle != null ? bundle.getString(SOURCE_KEY) : null;
		
		// Login button clicked
		ok = (Button) findViewById(R.id.loginBtnLogin);
		ok.setOnClickListener(this);
		exit = (Button) findViewById(R.id.loginBtnCancel);
		exit.setOnClickListener(this);

		result = (TextView) findViewById(R.id.loginLblResult);

		uname = (EditText) findViewById(R.id.loginTxtUsername);
		pword = (EditText) findViewById(R.id.loginTxtPassword);
		
		SharedPrefs sharedPrefs = SharedPrefs.getInstance();
		uname.setText(sharedPrefs.getUserName());
		pword.setText(sharedPrefs.getPassword());
		
		lblPassword = (TextView)findViewById(R.id.loginLblPassword);
		lblPassword.setOnClickListener(this);
		
		imgPassword = (ImageView) findViewById(R.id.loginImgPassword);
		imgPassword.setOnClickListener(this);
		
		showKeyBoard();
	}
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		dismissProgress();
		synchronized (lock) {
		}
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume() {
		if (running) {
			if (dialog != null) {
				dialog.show();
			} else {
				dismissProgress();
				dialog = ProgressDialog.show(this, "", getWaitMessage(), true);				
			}
		}		
		super.onResume();
		
	}



	private void alertDialog (final boolean success){
		AlertDialog.Builder builder;

		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.login_result,
		                               (ViewGroup) findViewById(R.id.layout_root));

		TextView text = (TextView) layout.findViewById(R.id.loginResultText);
		ImageView image = (ImageView) layout.findViewById(R.id.loginResultImg);
		Button btnClose = (Button) layout.findViewById(R.id.loginResultBtnOk);

		if (success) {
			image.setImageResource(R.drawable.ic_check);
			text.setText(getResources().getString(R.string.msgLoginSuccess));
		}
		else {
			image.setImageResource(R.drawable.ic_fail);
			text.setText(getResources().getString(R.string.msgLoginFailure));
		}

		builder = new AlertDialog.Builder(this);
		builder.setView(layout);
		final AlertDialog alertDialog = builder.create();
		btnClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				if (success) {
					LoginActivity.this.finish();
				}
			}
		});		
		dismissProgress();
		alertDialog.show();
	}

	
	private static boolean running = false;
	
	class LoginTask extends AsyncTask<Void, Void, LoginResponse> {

		protected LoginResponse doInBackground(Void... vs) {
			return postData();
		}

		protected void onProgressUpdate(Void... progress) {
		}
		

		@Override
		protected void onPreExecute() {
			running = true;
			hideKeyBoard();
			super.onPreExecute();
		}

		protected void onPostExecute(LoginResponse response) {
			running = false;
			dismissProgress();
			if (response.hasSession()) {
				SharedPrefs prefs = SharedPrefs.getInstance();
				prefs.setUserName(uname.getText().toString().trim());
				prefs.setPassword(pword.getText().toString().trim());
				if (Utility.isEmpty(sourceActivityName)) {
					finish();
					startActivity(new Intent("tr.com.netgis.MainActivity"));
				}
				else {
					alertDialog(true);					
				}
			}
			else {
				alertDialog(false);
			}				
		}
	};
		
	@Override
	protected void onPause() {
		super.onPause();
		dismissProgress();
	}


	private static Object lock = new Object();
	
	private void showKeyBoard() {
        this.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
	
	private void hideKeyBoard() {
        this.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }
	
	private LoginResponse postData() {
		String userName = uname.getText().toString().trim();
		LoginRequest loginRequest = new LoginRequest();
		loginRequest.setUserName(userName);
		loginRequest.setPassword(pword.getText().toString().trim());
		loginRequest.setShowFailureNotification(false);
		loginRequest.setServerUrl(Constants.SERVER_URL);
		return WebServisCaller.callWebService(loginRequest);
	}

	static ProgressDialog dialog;

	private void dismissProgress() {
		if (dialog != null) {
			dialog.dismiss();			
		}
	}

	private String getWaitMessage () {
		String waitMsg = getResources().getString(R.string.msgLoginWait);
		return waitMsg;
	}
	
	@Override
	public void onClick(View view) {
		if (view == ok) {
			String userName = uname.getText().toString().trim();
			if (Utility.isEmpty(userName)) {
				Toast.makeText(this, "Kullanıcı Adı'nı giriniz", Toast.LENGTH_SHORT).show();
				return;
			}
			dialog = ProgressDialog.show(this, "", getWaitMessage(), true);    			
			new LoginTask().execute();
		} else if (view == exit) {
			if (Utility.isEmpty(sourceActivityName)) {
				Utility.killApp(true);				
			} else {
				finish();
			}
		} else if (view == lblPassword || view == imgPassword) {
			if (pword.getTransformationMethod() == null)
				pword.setTransformationMethod(new PasswordTransformationMethod());
			else 
				pword.setTransformationMethod(null);			
		}
	}

}